package com.zzl.car.handle;

import com.zzl.car.context.ZdpResponseBody;
import com.zzl.car.context.ZdpResultCode;
import com.zzl.car.exception.ZdpException;
import com.zzl.car.zdpAnnotation.ExceptionMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;

@RestControllerAdvice
public class ZdpExceptionHandler {


    @Autowired
    private HttpServletResponse response;


    @ExceptionHandler(MethodArgumentNotValidException.class)



    public ZdpResponseBody MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) throws NoSuchFieldException {
        String defaultMessage = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        //拿到验证失败的对象class (错误字段)
        Class<?> parameterType = e.getParameter().getParameterType();
        String parameterName = e.getParameter().getParameterName(); //错误字段名
        Field declaredField = parameterType.getDeclaredField(parameterName);
        ExceptionMsg annotation = declaredField.getAnnotation(ExceptionMsg.class);
        if(annotation!=null){
            //直接封装注解的信息即可
            return new ZdpResponseBody(annotation.value(),annotation.message(),defaultMessage);
        }
        //从异常对象中拿到ObjectError对象
        return new ZdpResponseBody(ZdpResultCode.VALIDATE_FAILED,defaultMessage);//返回错误提示信息
    }

    @ExceptionHandler(ZdpException.class)
    public ZdpResponseBody zdpExceptionHandler(ZdpException e){
        //未登录抛出的错误
        response.setHeader("Access-Control-Allow-Origin","*");
        return new ZdpResponseBody(e.getCode(),e.getMsg(),null);
    }

    @ExceptionHandler(RuntimeException.class)
    public ZdpResponseBody runTimeExceptionHandler(RuntimeException e){
        response.setHeader("Access-Control-Allow-Origin","*");
        return new ZdpResponseBody(1005,"连接超时",null);
    }
}
